//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.sonar.server.ce.ws;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.ce.task.CeTask;
import org.sonar.db.ce.CeTaskCharacteristicDto;
import org.sonar.server.ce.queue.ReportSubmitter;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.ws.WsUtils;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Ce.SubmitResponse;

public class SubmitAction implements CeWsAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubmitAction.class);
    private static final String PARAM_PROJECT_KEY = "projectKey";
    private static final String PARAM_PROJECT_NAME = "projectName";
    private static final String PARAM_REPORT_DATA = "report";
    private static final String PARAM_ANALYSIS_CHARACTERISTIC = "characteristic";
    private final ReportSubmitter reportSubmitter;

    public SubmitAction(ReportSubmitter reportSubmitter) {
        this.reportSubmitter = reportSubmitter;
    }

    public void define(WebService.NewController controller) {
        WebService.NewAction action = controller.createAction("submit").setDescription("Submits a scanner report to the queue. Report is processed asynchronously. Requires analysis permission. If the project does not exist, then the provisioning permission is also required.").setPost(true).setInternal(true).setSince("5.2").setHandler(this).setResponseExample(this.getClass().getResource("submit-example.json"));
        action.createParam("projectKey").setRequired(true).setMaximumLength(400).setDescription("Key of project").setExampleValue("my_project");
        action.createParam("projectName").setRequired(false).setDescription("Optional name of the project, used only if the project does not exist yet. If name is longer than %d, it is abbreviated.", new Object[]{500}).setExampleValue("My Project");
        action.createParam("report").setRequired(true).setDescription("Report file. Format is not an API, it changes among SonarQube versions.");
        action.createParam("characteristic").setRequired(false).setDescription("Optional characteristic of the analysis. Can be repeated to define multiple characteristics.").setExampleValue("branchType=long").setSince("6.6");
    }

    public void handle(Request wsRequest, Response wsResponse) throws Exception {
        String projectKey = wsRequest.mandatoryParam("projectKey");
        String projectName = StringUtils.abbreviate((String)StringUtils.defaultIfBlank(wsRequest.param("projectName"), projectKey), 500);
        Map<String, String> characteristics = parseTaskCharacteristics(wsRequest);

        try {
            InputStream report = new BufferedInputStream(wsRequest.mandatoryParamAsPart("report").getInputStream());

            try {
                CeTask task = this.reportSubmitter.submit(projectKey, projectName, characteristics, report);
                Ce.SubmitResponse submitResponse = SubmitResponse.newBuilder().setTaskId(task.getUuid()).setProjectId(((CeTask.Component)task.getComponent().get()).getUuid()).build();
                WsUtils.writeProtobuf(submitResponse, wsRequest, wsResponse);
            } catch (Throwable var10) {
                try {
                    report.close();
                } catch (Throwable var9) {
                    var10.addSuppressed(var9);
                }

                throw var10;
            }

            report.close();
        } catch (IllegalStateException var11) {
            LOGGER.info(var11.getMessage(), var11);
            throw new ServerException(500, var11.getMessage());
        }
    }

    private static Map<String, String> parseTaskCharacteristics(Request wsRequest) {
        Map<String, String> characteristics = new LinkedHashMap();
        Iterator var2 = wsRequest.multiParam("characteristic").iterator();

        while(var2.hasNext()) {
            String param = (String)var2.next();
            String[] pair = StringUtils.split(param, "=", 2);
            BadRequestException.checkRequest(pair.length == 2, "Parameter '%s' must be a key-value pair with the format 'key=value'.", new Object[]{"characteristic"});
            BadRequestException.checkRequest(!characteristics.containsKey(pair[0]), "Key '%s' was provided twice with parameters '%s'", new Object[]{pair[0], "characteristic"});
            if (CeTaskCharacteristicDto.SUPPORTED_KEYS.contains(pair[0])) {
                characteristics.put(pair[0], pair[1]);
            }
        }

        return characteristics;
    }
}
